package pers.fulsun.demo.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 这种写法无法实现在配置文件中进行过滤器配置，需要手动关联路由
 *
 * @author fulsun
 * @create: 2021-08-16 00:33
 */
@Component //将GlobalTokenFilter注册成bean方可生效
@Slf4j
public class GlobalTokenFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器执行体
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 获取token
         */
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            log.error("您尚未登陆，请登陆后重试");
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            DataBuffer buffer = response.bufferFactory().wrap("您尚未登陆，请登陆后重试".getBytes());
            return response.writeWith(Mono.just(buffer));
        }

        /**
         * 继续执行下一过滤器/调用接口
         */
        return chain.filter(exchange);
    }

    /**
     * 设置当前过滤器的优先级，值越大，优先级越低
     */
    @Override
    public int getOrder() {
        return -100;
    }
}